<?php


namespace app\common\model;


use think\Model;

class Roles extends Model
{
    protected $pk = 'id';

    public function validate($data){
        if(empty($data['permission'])){wapAjaxReturn(400,'请选择权限');}
    }

    public function deal($data){
        $news = new self();

        if(empty($data['id'])){
            //新增
            $save = $news->allowField(true)->save($data);
        }else{
            //编辑
            $save = $news->allowField(true)->save($data,['id'=>$data['id']]);
        }

        if($save){
            //删除旧的角色权限，新增新权限进入
            RolePermission::destroy(['role_id'=>$news->id]);

            $rolePermission = new RolePermission();
            $list = array();
            foreach ($data['permission'] as $k=>$v){
                $list[$k]['role_id'] = $news->id;
                $list[$k]['permission_action'] = $v;
            }
            $rolePermission->saveAll($list);
        }

        $save ? wapAjaxReturn(0,'操作成功',[],'/admin/roles/list') :
            wapAjaxReturn(400,'操作失败');
    }


    public function getList(){
        return self::select()->toArray()
            ;
    }


}